package com.fast.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 作者：ylc
 * 时间：2018年05月28日16:23:00
 * 描述：文件操作工具类
 */
@Slf4j
public class FileUtil {

    public static void download(HttpServletRequest request, HttpServletResponse response, String path) {
        response.reset();//设置为没有缓存
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-Type", "application/force-download");
        OutputStream os = null;
        InputStream serverFile = null;
        try {
            //org.springframework.core.io.Resource fileRource = new ClassPathResource(path);
            File file = new File(path);
            response.setContentLength((int) file.length());
            response.setHeader("Content-disposition", "attachment;filename=" + new String(file.getName().getBytes(), "iso-8859-1"));
            os = response.getOutputStream();
            serverFile = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = serverFile.read(buffer)) > 0) {
                os.write(buffer, 0, count);
            }
        } catch (FileNotFoundException e) {
            log.error("文件下载失败", e);
        } catch (IOException e) {
            log.error("文件下载失败", e);
        } finally {
            IOUtils.closeQuietly(serverFile);
            IOUtils.closeQuietly(os);
        }
    }
}
